import { PageContainer } from '@ant-design/pro-layout';
import React, { useState, useRef ,useEffect  } from 'react';
import { history } from 'umi';
import { Space, message, Card, Modal, Descriptions, Divider,Button } from 'antd';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';

const { confirm } = Modal;
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import styles from './index.less';
import { queryDeviceList } from '@/services/device';
import CreateCommandForm from './components/CreateCommandForm';
import UpdateCommandForm from './components/UpdateCommandForm';
import CreateRuleForm from './components/CreateRuleForm';
import UpdateRuleForm from './components/UpdateRuleForm';

import { queryDevice } from '@/services/device';
import { queryDeviceAttrList } from '@/services/deviceattr';

import { queryDeviceLinkageRule,removeDeviceLinkageRule,updateDeviceLinkageRule,addDeviceLinkageRule } from '@/services/deviceLinkageRule';
import { queryDeviceLinkageCommand,removeDeviceLinkageCommand,updateDeviceLinkageCommand,addDeviceLinkageCommand } from '@/services/deviceLinkageCommand';




const DeviceLinkageDetail: React.FC = (props: any) => {
const { params } = props.match;
var { linkageInfo } = props.location.state;
  // linkageInfo = props.location.query ;
  console.log(linkageInfo)
const [formValues, setFormValues] = useState({});
const [createCommandModalVisible, handleCommandModalVisible] = useState<boolean>(false);
const [updateCommandModalVisible, handleUpdateCommandModalVisible] = useState<boolean>(false);

const [createRuleModalVisible, handleRuleModalVisible] = useState<boolean>(false);
const [updateRuleModalVisible, handleUpdateRuleModalVisible] = useState<boolean>(false);




/**
 * 添加规则
 * @param fields
 */
 const handleRuleAdd = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在添加');
  try {
    fields.linkageId=params.id;
    await addDeviceLinkageRule(fields);
    hide();
    resetForm();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};


/**
 * 更新规则
 * @param fields
 */
const handleRuleUpdate = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDeviceLinkageRule(fields);
    hide();
    resetForm();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};


//删除单个
const toremove = async (fields: any,type:number) => {
  try {
    if(type==1){
      await removeDeviceLinkageRule({id:fields.id,useState:(fields.useState==0?1:0)});
      actionRef.current?.reload();
    }else{
      await removeDeviceLinkageCommand({id:fields.id,useState:(fields.useState==0?1:0)});
      actionCommandRef.current?.reload();
    }
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    message.error('删除失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */
 const updateState = async (fields: any,type:number) => {
  try {
    if(type==1){
      await updateDeviceLinkageRule({id:fields.id,useState:(fields.useState==0?1:0)});
      actionRef.current?.reload();
    }else{
      await updateDeviceLinkageCommand({id:fields.id,useState:(fields.useState==0?1:0)});
      actionCommandRef.current?.reload();
    }
    
    message.success('更新成功');
 
    return true;
  } catch (error) {
    message.error('新失败请重试！');
    return false;
  }
};


const remove = async (fields: any,type:number) => {
console.log(fields)
  confirm({
    title: '您确定要删除吗?',
    icon: <ExclamationCircleOutlined />,
    async onOk() {
      await toremove(fields,type);
    },
    onCancel() {
      console.log('Cancel');
    },
  });
 
};


/**
 * 添加动作
 * @param fields
 */
 const handleCommandAdd = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在添加');
  try {
    fields.linkageId=params.id;
    await addDeviceLinkageCommand(fields);
    hide();
    resetForm();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};


/**
 * 更新动作
 * @param fields
 */
const handleCommandUpdate = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDeviceLinkageRule(fields);
    hide();
    resetForm();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

const actionRef = useRef<ActionType>();
const actionCommandRef = useRef<ActionType>();
const [deviceList, setDeviceList] = useState([]);
const [ruleList, setRuleList] = useState<API.DeviceLinkageRuleItem>([]);

const setSelectData = async () => {
  setDeviceList(await  queryDeviceList({useState:1}))  ; 
} 
const getAttrList = async (deviceId,type=0) => {
 return await   queryDeviceAttrList({deviceId,type,dataType:1});
} 


useEffect(() => {
  
  setSelectData();
}, []);

  const ruleColumns: ProColumns[] = [
    {
      title: '设备名称',
      dataIndex: 'deviceName'
    },

    {
      title: '变量名称',
      dataIndex: 'browseName'
    },
    {
      title: '是否启用',
      dataIndex: 'useState',
      valueType: 'radio',
      valueEnum: {
        1:  '启用',
        0:  '未启用',
      }
    },
    
    {
      title: '联动规则',
      dataIndex: 'valueRole'
    }, {
      title: '数值比较符号',
      dataIndex: 'symbol'
    },
    {
      title: '最大值',
      dataIndex: 'maxValue'
    }, {
      title: '最小值',
      dataIndex: 'minValue'
    },
    {
      title: '或并关系',
      dataIndex: 'andOr',
      valueEnum: {
        'and':"并且",
        'or': "或者",
      }
    },
   
   
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
        key="updateState"
        onClick={async () => {    await updateState( record,1)}} >
        {record.useState==0?'启用':'禁用'} 
        </a>, <a
          key="editable"
          onClick={async () => {
            handleUpdateRuleModalVisible(true);
            setFormValues(record);
          }}
        >
          编辑
        </a>, 
      <a onClick={async () => { await remove(record,1);   }}  >删除</a>
      ],
    },
  ];


  const commandColumns: ProColumns[] = [
    {
      title: '设备名称',
      dataIndex: 'deviceName'
    },

    {
      title: '变量名称',
      dataIndex: 'browseName'
    },
   
    
    {
      title: '变量赋值',
      dataIndex: 'attrValue'
    }, {
      title: '通讯指令模板',
      dataIndex: 'message'
    },
    {
      title: '反馈信息模板',
      dataIndex: 'reserve'
    }, 
    {
      title: '是否启用',
      dataIndex: 'useState',
      valueType: 'radio',
      valueEnum: {
        1:  '启用',
        0:  '未启用',
      }
    },
   
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
        key="updateState"
        onClick={async () => {    await updateState( record,2)}} >
        {record.useState==0?'启用':'禁用'} 
        </a>, <a
          key="editable"
          onClick={async () => {
            handleUpdateCommandModalVisible(true);
            setFormValues(record);
          }}
        >
          编辑
        </a>, 
      <a onClick={async () => { await remove(record);   }}  >删除</a>
      ],
    },
  ];

  const getAddBtn = function () {
    console.log(ruleList)
    if (ruleList.length>0) {
      return ( <Button icon={<PlusOutlined />} type="primary" onClick={() => handleCommandModalVisible(true)}>
      新增
     </Button>);
    }else{
      return null;
    }
  }
  return (
        <div className={styles.main}>
          <a   onClick={()=>history.goBack()}> 返回上一级  </a>
      <Card>
      <Descriptions  column={1}   title={<div>联动规则基本信息  {linkageInfo.useState==1?<span  className={styles.shebeiStateBtn} >启用</span>:<span   className={[styles.shebeiStateBtn, styles.defaultBtnBg].join(' ')} >未启用</span>}</div>}>
          <Descriptions.Item label="联动名称">{linkageInfo.name} ( {linkageInfo.isSuspend==1?' 暂停至 '+linkageInfo.suspendTime:' 正常 '}  )</Descriptions.Item>
      
          <Descriptions.Item label="联动描述">{linkageInfo.memo}</Descriptions.Item>
      
        </Descriptions>

    
   
       <Divider  className={styles.divider} />
        <div className={styles.titlerow}>
          <div className={styles.title}>联动条件配置</div>
          <div>   
            <Button icon={<PlusOutlined />} type="primary" onClick={() => handleRuleModalVisible(true)}>
              新增
            </Button>
          </div>
        </div>
        <ProTable
          style={{ marginBottom: 24 }}
          pagination={{
            defaultCurrent: 1,
            defaultPageSize: 10,
          }}
          search={false}
          options={false}
          actionRef={actionRef}
          columns={ruleColumns}
          //request={(param) => queryDeviceLinkageRule({...param,...params})}
          request={
            async ( param) => {
              var rules=  await queryDeviceLinkageRule({...param,...params,...{current:1,  pageSize:100}})
              setRuleList(rules.data)
              return rules;
          }
        }
          toolBarRender={false}
          rowKey="id"
        />
    <Divider  className={styles.divider} />
     
    
       <div className={styles.titlerow}>
          <div className={styles.title}>联动动作配置</div>
          <div> { getAddBtn()}  </div>
        </div>
     <ProTable
       style={{ marginBottom: 24 }}
       pagination={{
        defaultCurrent: 1,
        defaultPageSize: 10,
        }}
       search={false}
       options={false}
      
       actionRef={actionCommandRef}
       columns={commandColumns}
       // request={ async ( param) => {return  await  querySpecificDeviceAttr({ ...param })  }}
       request={(param) => queryDeviceLinkageCommand({...param,...params})}
    
        toolBarRender={false}
   
       rowKey="id"
     />

    
      </Card>
      <CreateRuleForm
        onSubmit={async (value,resetForm) => {
          value.useState=1;
          const success = await handleRuleAdd(value,resetForm);
          if (success) {
            handleRuleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleRuleModalVisible(false)}
    
        modalVisible={createRuleModalVisible}
        getAttrData={(deviceId,type) => getAttrList(deviceId,type)}
        deviceList={deviceList}
      />
    
      {formValues && Object.keys(formValues).length ? (
        <UpdateRuleForm
          onSubmit={async (value,resetForm) => {
            const success = await handleRuleUpdate(value,resetForm);
            if (success) {
              handleUpdateRuleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateRuleModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateRuleModalVisible}
          values={formValues}
          getAttrData={(deviceId) => getAttrList(deviceId)}
         deviceList={deviceList}
        />
      ) : null}
         <CreateCommandForm
        onSubmit={async (value,resetForm) => {
          value.useState=1;
          const success = await handleCommandAdd(value,resetForm);
          if (success) {
            handleCommandModalVisible(false);
            if (actionCommandRef.current) {
              actionCommandRef.current.reload();
            }
          }
        }}
        onCancel={() => handleCommandModalVisible(false)}
        modalVisible={createCommandModalVisible}
        getAttrData={(deviceId) => getAttrList(deviceId)}
        deviceList={deviceList}
       
      />
    
      {formValues && Object.keys(formValues).length ? (
        <UpdateCommandForm
          onSubmit={async (value,resetForm) => {
            const success = await handleCommandUpdate(value,resetForm);
            if (success) {
              handleUpdateCommandModalVisible(false);
              setFormValues({});
              if (actionCommandRef.current) {
                actionCommandRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateCommandModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateCommandModalVisible}
          values={formValues}
          getAttrData={(deviceId) => getAttrList(deviceId)}
           deviceList={deviceList}
        />
      ) : null}
    </div>
  );
};

export default DeviceLinkageDetail;